#ifndef INDEX_HTML_H
#define INDEX_HTML_H

const char INDEX_HTML[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>车辆控制</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            margin: 0;
            padding: 0;
            background-color: #f0f0f0;
            color: #333;
            touch-action: none;
            overflow: hidden;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        h1 {
            color: #2c3e50;
            margin-bottom: 20px;
        }
        .joystick-container {
            position: relative;
            width: 300px;
            height: 300px;
            margin: 0 auto;
            background-color: #ddd;
            border-radius: 50%;
            box-shadow: inset 0 0 20px rgba(0,0,0,0.2);
            touch-action: none;
        }
        .joystick-knob {
            position: absolute;
            width: 80px;
            height: 80px;
            background-color: #3498db;
            border-radius: 50%;
            top: 50%;
            left: 50%;
            margin-left: -40px;
            margin-top: -40px;
            box-shadow: 0 0 10px rgba(0,0,0,0.3);
            cursor: pointer;
            touch-action: none;
        }
        .status {
            margin-top: 20px;
            padding: 10px;
            background-color: #fff;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        .sensor-data {
            margin-top: 20px;
            padding: 10px;
            background-color: #fff;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            text-align: left;
        }
        .sensor-data h3 {
            margin-top: 0;
            color: #2c3e50;
        }
        .sensor-data p {
            margin: 5px 0;
        }
        /* PID调参样式 */
        .pid-tuning {
            margin-top: 20px;
            padding: 10px;
            background-color: #fff;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            text-align: left;
        }
        .pid-tuning h3 {
            margin-top: 0;
            color: #2c3e50;
        }
        .pid-group {
            margin-bottom: 15px;
        }
        .pid-group h4 {
            margin: 5px 0;
            color: #3498db;
        }
        .pid-controls {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 10px;
        }
        .pid-control {
            display: flex;
            flex-direction: column;
            width: calc(33% - 10px);
        }
        .pid-control label {
            font-weight: bold;
            margin-bottom: 3px;
        }
        .pid-control input {
            width: 100%;
            padding: 5px;
            border: 1px solid #ccc;
            border-radius: 3px;
        }
        .pid-buttons {
            display: flex;
            gap: 10px;
            margin-top: 10px;
        }
        .pid-buttons button {
            padding: 8px 15px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
        }
        .pid-buttons button:hover {
            background-color: #2980b9;
        }
        .tab-container {
            margin-top: 20px;
        }
        .tab-buttons {
            display: flex;
            margin-bottom: 10px;
        }
        .tab-button {
            padding: 10px 20px;
            background-color: #ddd;
            border: none;
            cursor: pointer;
            flex: 1;
        }
        .tab-button.active {
            background-color: #3498db;
            color: white;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>车辆控制</h1>
        
        <div class="tab-container">
            <div class="tab-buttons">
                <button class="tab-button active" data-tab="control-tab" onclick="openTab(event, 'control-tab')">控制</button>
                <button class="tab-button" data-tab="pid-tab" onclick="openTab(event, 'pid-tab')">PID调参</button>
            </div>
            
            <div id="control-tab" class="tab-content active">
                <div class="joystick-container" id="joystick-container">
                    <div class="joystick-knob" id="joystick-knob"></div>
                </div>
                
                <div class="status">
                    <p>前进速度: <span id="forward-value">0.00</span></p>
                    <p>转向速度: <span id="turn-value">0.00</span></p>
                </div>
                
                <div class="sensor-data">
                    <h3>传感器数据</h3>
                    <p>角度: Roll=<span id="roll">0.0</span>° Pitch=<span id="pitch">0.0</span>° Yaw=<span id="yaw">0.0</span>°</p>
                    <p>目标角度: <span id="target-angle">0.0</span>°</p>
                    <p>温度: <span id="temp">0.0</span>°C</p>
                    <p>电机1: 角度=<span id="motor1-angle">0.0</span>° 速度=<span id="motor1-speed">0.0</span> RPM</p>
                    <p>电机2: 角度=<span id="motor2-angle">0.0</span>° 速度=<span id="motor2-speed">0.0</span> RPM</p>
                </div>
            </div>
            
            <div id="pid-tab" class="tab-content">
                <div class="pid-tuning">
                    <h3>PID参数调整</h3>
                    
                    <div class="pid-group">
                        <h4>姿态稳定PID (pid_stb)</h4>
                        <div class="pid-controls">
                            <div class="pid-control">
                                <label for="pid_stb_p">P值:</label>
                                <input type="number" id="pid_stb_p" step="0.01" value="0.60">
                            </div>
                            <div class="pid-control">
                                <label for="pid_stb_i">I值:</label>
                                <input type="number" id="pid_stb_i" step="0.01" value="0.00">
                            </div>
                            <div class="pid-control">
                                <label for="pid_stb_d">D值:</label>
                                <input type="number" id="pid_stb_d" step="0.01" value="0.02">
                            </div>
                        </div>
                    </div>
                    
                    <div class="pid-group">
                        <h4>速度PID (pid_vel)</h4>
                        <div class="pid-controls">
                            <div class="pid-control">
                                <label for="pid_vel_p">P值:</label>
                                <input type="number" id="pid_vel_p" step="0.01" value="0.60">
                            </div>
                            <div class="pid-control">
                                <label for="pid_vel_i">I值:</label>
                                <input type="number" id="pid_vel_i" step="0.01" value="0.00">
                            </div>
                            <div class="pid-control">
                                <label for="pid_vel_d">D值:</label>
                                <input type="number" id="pid_vel_d" step="0.01" value="0.01">
                            </div>
                        </div>
                    </div>
                    
                    <div class="pid-buttons">
                        <button onclick="getPIDValues()">获取当前值</button>
                        <button onclick="applyPIDValues()">应用设置</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 等待DOM完全加载后再初始化
        document.addEventListener('DOMContentLoaded', function() {
            initJoystick();
            initTabs();
            
            // 初始加载传感器数据
            updateSensorData();
            
            // 每秒更新一次传感器数据
            setInterval(updateSensorData, 1000);
        });
        
        // 标签页切换功能
        function initTabs() {
            // 添加标签切换事件
            document.querySelectorAll('.tab-button').forEach(button => {
                button.addEventListener('click', function(e) {
                    // 获取标签页名称，优先使用data-tab属性，否则使用按钮文本生成ID
                    const tabId = this.getAttribute('data-tab');
                    if (tabId) {
                        openTab(e, tabId);
                    } else {
                        // 从按钮文本生成标签ID
                        const text = this.textContent.trim().toLowerCase();
                        const tabName = text.replace(/\s+/g, '-') + '-tab';
                        console.log("生成的标签ID: " + tabName); // 调试输出
                        openTab(e, tabName);
                    }
                });
            });
            
            // 调试输出找到的标签按钮
            console.log("找到标签按钮数量: " + document.querySelectorAll('.tab-button').length);
        }
        
        function openTab(evt, tabName) {
            var i, tabcontent, tabbuttons;
            
            // 隐藏所有标签内容
            tabcontent = document.getElementsByClassName("tab-content");
            for (i = 0; i < tabcontent.length; i++) {
                tabcontent[i].classList.remove("active");
            }
            
            // 移除所有标签按钮的活动状态
            tabbuttons = document.getElementsByClassName("tab-button");
            for (i = 0; i < tabbuttons.length; i++) {
                tabbuttons[i].classList.remove("active");
            }
            
            // 显示当前标签内容并添加活动状态
            document.getElementById(tabName).classList.add("active");
            evt.currentTarget.classList.add("active");
            
            // 调试输出，帮助排查问题
            console.log("切换到标签页: " + tabName);
        }
        
        // 虚拟摇杆控制初始化
        function initJoystick() {
            const joystickContainer = document.getElementById('joystick-container');
            const joystickKnob = document.getElementById('joystick-knob');
            const forwardValue = document.getElementById('forward-value');
            const turnValue = document.getElementById('turn-value');
            
            let isDragging = false;
            let containerRect = joystickContainer.getBoundingClientRect();
            let containerCenterX = containerRect.width / 2;
            let containerCenterY = containerRect.height / 2;
            let containerRadius = Math.min(containerRect.width, containerRect.height) / 2;
            let knobRadius = joystickKnob.offsetWidth / 2;
            let maxDistance = containerRadius - knobRadius;
            
            let currentForward = 0;
            let currentTurn = 0;
            
            // 记录上一次发送的数值
            let lastForward = 0;
            let lastTurn = 0;
            let lastSendTime = 0;
            const sendInterval = 100; // 限制发送频率（毫秒）
            const zeroValueInterval = 500; // 当值为0时的发送间隔（毫秒）
            
            // 重新计算容器尺寸（响应窗口大小变化）
            function updateContainerDimensions() {
                containerRect = joystickContainer.getBoundingClientRect();
                containerCenterX = containerRect.width / 2;
                containerCenterY = containerRect.height / 2;
                containerRadius = Math.min(containerRect.width, containerRect.height) / 2;
                maxDistance = containerRadius - knobRadius;
            }
            
            // 触摸和鼠标事件处理
            function handleStart(e) {
                isDragging = true;
                updateContainerDimensions(); // 确保尺寸是最新的
                handleMove(e);
            }
            
            function handleMove(e) {
                if (!isDragging) return;
                
                e.preventDefault();
                
                let clientX, clientY;
                
                if (e.type.startsWith('touch')) {
                    if (e.touches.length === 0) return; // 防止触摸事件没有触摸点
                    clientX = e.touches[0].clientX;
                    clientY = e.touches[0].clientY;
                } else {
                    clientX = e.clientX;
                    clientY = e.clientY;
                }
                
                const rect = joystickContainer.getBoundingClientRect();
                const offsetX = clientX - (rect.left + containerCenterX);
                const offsetY = clientY - (rect.top + containerCenterY);
                
                // 计算距离和角度
                const distance = Math.sqrt(offsetX * offsetX + offsetY * offsetY);
                const angle = Math.atan2(offsetY, offsetX);
                
                // 限制摇杆在容器内
                const limitedDistance = Math.min(distance, maxDistance);
                
                // 计算新位置
                const newX = limitedDistance * Math.cos(angle);
                const newY = limitedDistance * Math.sin(angle);
                
                // 更新摇杆位置
                joystickKnob.style.transform = `translate(${newX}px, ${newY}px)`;
                
                // 计算控制值（-1到1范围）
                let newForward = -newY / maxDistance;  // 向上为正，向下为负
                let newTurn = newX / maxDistance;      // 向右为正，向左为负
                
                // 添加死区，忽略很小的变化（防抖动）
                const deadZone = 0.05;
                if (Math.abs(newForward) < deadZone) newForward = 0;
                if (Math.abs(newTurn) < deadZone) newTurn = 0;
                
                // 应用平滑过渡
                const smoothFactor = 0.8; // 值越大，过渡越平滑
                currentForward = currentForward * smoothFactor + newForward * (1 - smoothFactor);
                currentTurn = currentTurn * smoothFactor + newTurn * (1 - smoothFactor);
                
                // 显示数值（保留两位小数）
                forwardValue.textContent = currentForward.toFixed(2);
                turnValue.textContent = currentTurn.toFixed(2);
                
                // 发送控制数据
                sendControlData();
            }
            
            function handleEnd(e) {
                if (!isDragging) return;
                isDragging = false;
                
                // 回到中心位置
                joystickKnob.style.transform = 'translate(0px, 0px)';
                
                // 重置控制值
                currentForward = 0;
                currentTurn = 0;
                
                // 更新显示
                forwardValue.textContent = '0.00';
                turnValue.textContent = '0.00';
                
                // 强制立即发送停止命令（不考虑时间间隔限制）
                const data = {
                    turn: 0,
                    forward: 0
                };
                
                fetch('/control', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                })
                .catch(error => {
                    console.error('发送停止命令失败:', error);
                });
                
                console.log('发送停止命令: 前进=0.00, 转向=0.00');
                
                // 更新上次发送的值和时间
                lastForward = 0;
                lastTurn = 0;
                lastSendTime = Date.now();
            }
            
            // 发送控制数据到服务器
            function sendControlData() {
                const now = Date.now();
                if (now - lastSendTime < sendInterval) return;
                
                // 检查数值是否有变化
                const forwardVal = parseFloat(currentForward.toFixed(2));
                const turnVal = parseFloat(currentTurn.toFixed(2));
                
                // 判断是否为零值状态
                const isZeroState = forwardVal === 0 && turnVal === 0;
                
                // 确定发送间隔
                const currentInterval = isZeroState ? zeroValueInterval : sendInterval;
                
                // 只有当数值变化或者达到发送间隔时才发送
                if (forwardVal !== lastForward || 
                    turnVal !== lastTurn || 
                    now - lastSendTime >= currentInterval) {
                    
                    lastSendTime = now;
                    lastForward = forwardVal;
                    lastTurn = turnVal;
                    
                    const data = {
                        turn: turnVal,
                        forward: forwardVal
                    };
                    
                    fetch('/control', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(data)
                    })
                    .catch(error => {
                        console.error('发送控制数据失败:', error);
                    });
                    
                    // 添加状态标记，零值状态显示不同的信息
                    const statusMsg = isZeroState ? "零值状态" : "活动状态";
                    console.log(`发送控制(${statusMsg}): 前进=${forwardVal}, 转向=${turnVal}`);
                }
            }
            
            // 添加事件监听
            joystickContainer.addEventListener('mousedown', handleStart);
            document.addEventListener('mousemove', handleMove);
            document.addEventListener('mouseup', handleEnd);
            document.addEventListener('mouseleave', handleEnd); // 鼠标离开窗口时也停止
            
            joystickContainer.addEventListener('touchstart', handleStart, { passive: false });
            document.addEventListener('touchmove', handleMove, { passive: false });
            document.addEventListener('touchend', handleEnd);
            document.addEventListener('touchcancel', handleEnd);
            
            // 监听窗口大小变化
            window.addEventListener('resize', updateContainerDimensions);
            
            // 初始化时确保尺寸计算正确
            setTimeout(updateContainerDimensions, 100);
        }
        
        // 获取当前PID值
        function getPIDValues() {
            fetch('/get-pid')
            .then(response => response.json())
            .then(data => {
                // 更新姿态稳定PID值
                document.getElementById('pid_stb_p').value = data.pid_stb.p;
                document.getElementById('pid_stb_i').value = data.pid_stb.i;
                document.getElementById('pid_stb_d').value = data.pid_stb.d;
                
                // 更新速度PID值
                document.getElementById('pid_vel_p').value = data.pid_vel.p;
                document.getElementById('pid_vel_i').value = data.pid_vel.i;
                document.getElementById('pid_vel_d').value = data.pid_vel.d;
                
                alert('PID参数获取成功');
            })
            .catch(error => {
                console.error('获取PID参数失败:', error);
                alert('获取PID参数失败');
            });
        }
        
        // 应用PID值
        function applyPIDValues() {
            const data = {
                pid_stb: {
                    p: parseFloat(document.getElementById('pid_stb_p').value),
                    i: parseFloat(document.getElementById('pid_stb_i').value),
                    d: parseFloat(document.getElementById('pid_stb_d').value)
                },
                pid_vel: {
                    p: parseFloat(document.getElementById('pid_vel_p').value),
                    i: parseFloat(document.getElementById('pid_vel_i').value),
                    d: parseFloat(document.getElementById('pid_vel_d').value)
                }
            };
            
            fetch('/set-pid', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    alert('PID参数设置成功');
                } else {
                    alert('PID参数设置失败: ' + result.message);
                }
            })
            .catch(error => {
                console.error('设置PID参数失败:', error);
                alert('设置PID参数失败');
            });
        }
        
        // 定期获取传感器数据
        function updateSensorData() {
            fetch('/sensor-data')
            .then(response => response.json())
            .then(data => {
                document.getElementById('roll').textContent = data.roll.toFixed(1);
                document.getElementById('pitch').textContent = data.pitch.toFixed(1);
                document.getElementById('yaw').textContent = data.yaw.toFixed(1);
                document.getElementById('temp').textContent = data.temp.toFixed(1);
                document.getElementById('motor1-angle').textContent = data.motor1Angle.toFixed(1);
                document.getElementById('motor1-speed').textContent = data.motor1Speed.toFixed(1);
                document.getElementById('motor2-angle').textContent = data.motor2Angle.toFixed(1);
                document.getElementById('motor2-speed').textContent = data.motor2Speed.toFixed(1);
                document.getElementById('target-angle').textContent = data.targetAngle.toFixed(1);
            })
            .catch(error => {
                console.error('获取传感器数据失败:', error);
            });
        }
    </script>
</body>
</html>
)rawliteral";

#endif // INDEX_HTML_H 